package com.hanbang.taitaigou.ui.widget.autoloadding;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.ListView;

import com.hanbang.taitaigou.utils.http.PagingHelp;


/**
 * Created by Administrator on 2016/3/14.
 */
public class ListViewForAutoLoad extends ListView implements StatusChangListener {
    private LoadState state = LoadState.None;
    private OnLoaddingListener onLoaddingListener;
    private FooterView footerView;


    public ListViewForAutoLoad(Context context) {
        this(context, null);
    }

    public ListViewForAutoLoad(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ListViewForAutoLoad(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        footerView = new FooterView(context);
        addFooterView(footerView);
        footerView.setVisibility(GONE);
        footerView.setStatus(LoadState.None);
        setOnScrollListener(new ScrollListener());
    }

    private final class ScrollListener implements OnScrollListener {
        private int lastItemIndex;//当前ListView中最后一个Item的索引
        private int totalItemCount;

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (lastItemIndex + getFooterViewsCount() + getHeaderViewsCount() >= totalItemCount) {// 达到数据的最后一条记录
                if (totalItemCount > 1 && state == LoadState.None && onLoaddingListener != null) {//可以加载
                    setState(LoadState.Loadding);
                    onLoaddingListener.onLoadding();
                }
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            lastItemIndex = getLastVisiblePosition(); // 获取当前屏幕最后Item的ID
            this.totalItemCount = totalItemCount;
        }
    }

    public LoadState getState() {
        return state;
    }

    public void setState(LoadState state) {
        this.state = state;
        footerView.setStatus(state);
    }

    public OnLoaddingListener getOnLoaddingListener() {
        return onLoaddingListener;
    }

    public void setOnLoaddingListener(OnLoaddingListener onLoaddingListener, PagingHelp pagingHelp) {
        this.onLoaddingListener = onLoaddingListener;
        pagingHelp.setStatusChangListener(this);
    }

    @Override
    public void loaddingFinsh() {
        if (state == LoadState.Loadding) {
            setState(LoadState.None);
        }
    }

    /**
     * 没有更多数据加载
     */
    @Override
    public void complete() {
        setState(LoadState.Complete);
    }

    @Override
    /**
     * 初始化状态
     */
    public void initState() {
        setState(LoadState.None);
    }
}
